package com.jahe.learn.netty4.customcodec;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketCloseStatus;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 超时，关闭连接。
 * @author: jahe.lai
 * @create: 2019-12-25 17:11
 */
public class IdleTimeOutHandler extends ChannelInboundHandlerAdapter {

    // 单实例
    final static IdleTimeOutHandler INSTANCE;

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent)evt;

            String eventType = null;
            switch (event.state()) {
                case ALL_IDLE:
                    eventType = "读写都空闲";
                    break;
                case READER_IDLE:
                    eventType = "读空闲";
                    break;
                case WRITER_IDLE:
                    eventType = "写空闲";
                    break;
            }
            System.out.println(ctx.channel().remoteAddress() + " 超时事件：" + eventType );
            // websocket的关闭协议
//            ctx.channel().writeAndFlush(new CloseWebSocketFrame(WebSocketCloseStatus.NORMAL_CLOSURE, eventType));
            ctx.channel().close();
        }
    }

    private IdleTimeOutHandler(){}

    static {
        INSTANCE = new IdleTimeOutHandler();
    }

}
